# -*- coding: utf-8 -*-

from odoo import fields, api
from odoo_contrib import models as contrib_models


class CheckIn(contrib_models.SchemaModel):
    _name = 'exhibition.checkin'
    _order = 'write_date desc'

    wechat_uid = fields.Many2one(
        'wechat.user',
        required=True,
    )
    salesman_id = fields.Many2one(
        'exhibition.users',
    )

    wechat_user_id = fields.Integer(string='用户id', related='wechat_uid.id')
    wechat_user_openid = fields.Char(string='用户openid', related='wechat_uid.openid')
    wechat_user_nickname = fields.Char(string='用户昵称', related='wechat_uid.nickname')
    wechat_user_avatar = fields.Char(string='用户头像', related='wechat_uid.avatar')

    salesman_name = fields.Char(string='销售名称', related='salesman_id.name')
    salesman_login = fields.Char(string='销售登录名', related='salesman_id.login')
    salesman_no = fields.Char(string='销售编号', related='salesman_id.salesman_no')

    checked_in_department_name = fields.Char(string='本次签到部门', related='salesman_id.department.name')
    first_checked_in_department_name = fields.Char(string='首次签到部门', related='wechat_uid.checked_in_department.name')

    @api.model
    def qrcode_scanned(self, scanner):
        return self.create({
            'wechat_uid': scanner.id
        })

    @api.multi
    def salesman_specified(self, salesman, wechat_user):
        for checkin in self:
            checkin.salesman_id = salesman.id
        if not wechat_user.checked_in_salesman:
            wechat_user.sudo().write({
                'checked_in_salesman': salesman.id,
                'checked_in_department': salesman.department.id,
            })
        return self
